package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.ProductStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.handler.ShareImageHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品类
 *
 * @author admin
 */
@Controller
@RequestMapping("/app/product")
public class YgProductController extends BaseController {

    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private YgSearchKeywordsService ygSearchKeywordsService;
    @Autowired
    private YgProductRecommendService ygProductRecommendService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private ShareImageHandler shareImageHandler;

    /**
     * 商品详情页
     *
     * @param id 商品id
     * @return
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public ResponseEntity detail(@RequestParam Long id) {
        YgProductModel product = ygProductService.findDetailModelForYjdian(id);
        return ResponseEntity.success(product);
    }


    @RequestMapping(value = "/selectProductByGroupId")
    @ResponseBody
    public ResponseEntity selectProductByGroupId(@RequestParam Long groupId) {
        List<Map<String, Object>> products = ygProductService.findProductByGroupId(0L, groupId);
        return ResponseEntity.success(products);
    }


    /**
     * 相似商品
     *
     * @return
     */
    @RequestMapping(value = "/similarityProduct")
    @ResponseBody
    public ResponseEntity similarityProduct(@RequestParam String brandName, @RequestParam() Long categoryId) {
        List<YgSimilarProductModel> result = ygProductService.findSimilarityProduct(brandName, categoryId);
        return ResponseEntity.success(result);
    }

    /**
     * 根据用户id查询购买过的商品
     *
     * @return
     */
    @RequestMapping(value = "/findProduct4ShaidanModel")
    @ResponseBody
    public ResponseEntity findProduct4ShaidanModel(QueryInfo queryInfo) {
        ResultSet<YgProduct4ShaidanModel> result =
                ygProductService.findProduct4ShaidanModel(queryInfo, SessionUtil.getCurrentUser().getId());
        return ResponseEntity.success(result.getResult());
    }

    /**
     * 商品列表页
     *
     * @param param 列表页参数
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity list(ProductListRequestParam param) {
        List<YgProduct4ListModel> result = ygProductService.findListForYjdian(param);
        return ResponseEntity.success(result);
    }


    /**
     * 商品列表页
     *
     * @param queryInfo 分页
     * @param sortKey   排序列
     * @param dir       排序方式
     * @param packId    自选包id
     * @return
     */
    @RequestMapping(value = "/listByPack")
    @ResponseBody
    public ResponseEntity listByPack(QueryInfo queryInfo, String sortKey, String dir, Long packId) {
        if (!StringUtils.isBlank(sortKey)) {
            queryInfo.setSortKey(sortKey);
        }
        if (!StringUtils.isBlank(dir)) {
            queryInfo.setOrderByClause(dir);
        }
        List<YgProduct4ListModel> result = ygProductService.findListByPack(queryInfo, packId, SALES_PLATFORM);
        return ResponseEntity.success(result);
    }

    /**
     * 商品列表页
     *
     * @return
     */
    @RequestMapping(value = "/listByBmdism")
    @ResponseBody
    public ResponseEntity listByBmdism(QueryInfo queryInfo, String sortKey, String dir, Long bmdismId) {
        if (!StringUtils.isBlank(sortKey)) {
            queryInfo.setSortKey(sortKey);
        }
        if (!StringUtils.isBlank(dir)) {
            queryInfo.setOrderByClause(dir);
        }
        List<YgProduct4ListModel> result = ygProductService.findListByBmdism(queryInfo, bmdismId, SALES_PLATFORM);
        return ResponseEntity.success(result);
    }


    @RequestMapping(value = "/getSearchKeywords")
    @ResponseBody
    public ResponseEntity getSearchKeywords() {
        Map<String, List<String>> searchKeywords = ygSearchKeywordsService.findSearchKeywords();

        return ResponseEntity.success(searchKeywords);
    }

    @RequestMapping("/getProductRecommend")
    @ResponseBody
    public ResponseEntity getProductRecommend(QueryInfo queryInfo, @RequestParam Long groupId) {
        List<YgProductRecommendModel> list = ygProductRecommendService.findProductByGroupId(queryInfo, groupId);
        return ResponseEntity.success(list);
    }


    @RequestMapping("/getProductListBySupplierId")
    @ResponseBody
    public ResponseEntity getProductListBySupplierId(@RequestParam Long supplierId) {
        List<Map<String, Object>> ygProduct = ygProductService.findProductListBySupplierId(supplierId);
        return ResponseEntity.success(ygProduct);
    }

    /**
     * 商品列表页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPreDateProduct")
    @ResponseBody
    public ResponseEntity getPreDateProduct(QueryInfo queryInfo) {
        List<YgProduct> result = ygProductService.find(queryInfo, null, null,
                ProductStatus.OnSale.name(), 1L, true);
        return ResponseEntity.success(result);
    }

    @RequestMapping(value = "/getVipProduct")
    @ResponseBody
    public ResponseEntity getVipProduct() {
        String string = redisDao.get("vipskuinfo");
        Map<String, Object> map = new HashMap<>();
        List<YgSkuInfo> list = JSON.parseObject(string, new TypeReference<List<YgSkuInfo>>() {
        });
        if (list != null) {
            map.put("skuList", list);
        }
        String str = redisDao.get(RedisConstant.VIP_KEY);
        Map pricemap = JSONObject.parseObject(str, Map.class);
        if (pricemap != null) {
            map.put("sourceVipPrice", pricemap.get("sourceVipPrice"));
            map.put("vipPrice", pricemap.get("vipPrice"));
        }
        return ResponseEntity.success(map);
    }

    /**
     * 分享商品图（带分享source用户）
     *
     * @param imageReq imageReq
     * @return
     */
    @RequestMapping(value = "shareProduct")
    @ResponseBody
    public ResponseEntity shareProduct(ShareProductImageReq imageReq) {
        imageReq.setShareUserId(SessionUtil.getCurrentUser().getId());
        imageReq.setPlatformNo(PLATFORM_NO);
        try {
            return ResponseEntity.success(shareImageHandler.shareProduct(imageReq));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.error("生成分享图异常，请稍后重试", null);
        }
    }

    /**
     * 推荐拼团商品
     *
     * @param salesPlatform 销售平台（必传）
     * @return
     */
    @RequestMapping("groupProductForRecommend")
    @ResponseBody
    public ResponseEntity groupProductForRecommend(@RequestParam(defaultValue = "Yijiadian") String salesPlatform,
                                                   @RequestParam(defaultValue = "false") Boolean skipYg) {
        return ResponseEntity.success(
                ygProductService.productListByGroupOrder(new QueryInfo(12), salesPlatform, "拼团推荐", skipYg));
    }

    /**
     * 指定销售属性的拼团列表
     *
     * @param queryInfo     分页
     * @param tags          销售属性
     * @param salesPlatform 销售平台（必传）
     * @return
     */
    @RequestMapping("groupProductByTags")
    @ResponseBody
    public ResponseEntity groupProductByTags(QueryInfo queryInfo, String tags,
                                             @RequestParam(defaultValue = "Yijiadian") String salesPlatform,
                                             @RequestParam(defaultValue = "false") Boolean skipYg) {
        return ResponseEntity.success(
                ygProductService.productListByGroupOrder(queryInfo, salesPlatform, tags, skipYg));
    }

    @RequestMapping(value = "/findSku", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findSku(@RequestParam Long productId) {
        List<YgSkuModel> skuList = ygProductService.findSku(productId);
        return ResponseEntity.success(skuList);
    }

}
